import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('user') || '{}'))
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const username = computed(() => userInfo.value.account || '')

  // 登录
  const login = async (loginData) => {
    try {
      console.log('Store: 开始登录，数据:', loginData)
      loading.value = true
      const response = await authAPI.login(loginData)
      console.log('Store: API响应:', response)

      if (response.code === 200) {
        console.log('Store: 登录成功，设置token')
        token.value = response.value // 后端返回的是value字段
        localStorage.setItem('token', response.value)

        // 获取用户信息
        console.log('Store: 获取用户信息')
        await getUserInfo()

        ElMessage.success('登录成功')
        return { success: true }
      } else {
        console.log('Store: 登录失败:', response.msg) // 后端返回的是msg字段
        ElMessage.error(response.msg || '登录失败')
        return { success: false, message: response.msg }
      }
    } catch (error) {
      console.error('Store: 登录错误:', error)
      ElMessage.error('登录失败，请检查网络连接')
      return { success: false, message: '登录失败' }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerData) => {
    try {
      loading.value = true
      const response = await authAPI.register(registerData)

      if (response.code === 200) {
        ElMessage.success('注册成功，请登录')
        return { success: true }
      } else {
        ElMessage.error(response.msg || '注册失败') // 后端返回的是msg字段
        return { success: false, message: response.msg }
      }
    } catch (error) {
      console.error('注册错误:', error)
      ElMessage.error('注册失败，请检查网络连接')
      return { success: false, message: '注册失败' }
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await authAPI.getUserInfo()
      if (response.code === 200) {
        userInfo.value = response.value // 后端返回的是value字段
        localStorage.setItem('user', JSON.stringify(response.value))
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 退出登录
  const logout = () => {
    authAPI.logout()
    token.value = ''
    userInfo.value = {}
    ElMessage.success('已退出登录')
  }

  // 初始化用户信息
  const initUserInfo = () => {
    if (token.value) {
      getUserInfo()
    }
  }

  // 修改角色后刷新用户信息
  const refreshUserInfo = async () => {
    await getUserInfo()
  }

  return {
    // 状态
    token,
    userInfo,
    loading,

    // 计算属性
    isLoggedIn,
    username,

    // 方法
    login,
    register,
    getUserInfo,
    logout,
    initUserInfo,
    refreshUserInfo
  }
})
